package com.mune.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.mune.common.exception.NoStockException;
import com.mune.common.to.MemberSessionTo;
import com.mune.common.to.mq.SeckillOrderTo;
import com.mune.common.to.order.OrderTo;
import com.mune.common.utils.R;
import com.mune.gulimall.order.constant.OrderConstant;
import com.mune.gulimall.order.entity.OrderItemEntity;
import com.mune.common.enume.OrderStatusEnum;
import com.mune.gulimall.order.entity.PaymentInfoEntity;
import com.mune.gulimall.order.feign.CartFeignService;
import com.mune.gulimall.order.feign.MemberFeignService;
import com.mune.gulimall.order.feign.ProductFeignService;
import com.mune.gulimall.order.feign.WareFeignService;
import com.mune.gulimall.order.interceptor.LoginUserInterceptor;
import com.mune.gulimall.order.service.OrderItemService;
import com.mune.gulimall.order.service.PaymentInfoService;
import com.mune.gulimall.order.to.OrderCreateTo;
import com.mune.gulimall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mune.common.utils.PageUtils;
import com.mune.common.utils.Query;

import com.mune.gulimall.order.dao.OrderDao;
import com.mune.gulimall.order.entity.OrderEntity;
import com.mune.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
  ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();
  @Autowired
  OrderItemService orderItemService;
  @Autowired
  MemberFeignService memberFeignService;
  @Autowired
  ThreadPoolExecutor executor;
  @Autowired
  CartFeignService cartFeignService;
  @Autowired
  WareFeignService wareFeignService;
  @Autowired
  RedisTemplate<String, Object> redisTemplate;
  @Autowired
  ProductFeignService productFeignService;
  @Autowired
  RabbitTemplate rabbitTemplate;
  @Autowired
  PaymentInfoService paymentInfoService;

  @Override

  public PageUtils queryPage(Map<String, Object> params) {
    IPage<OrderEntity> page = this.page(
            new Query<OrderEntity>().getPage(params),
            new QueryWrapper<OrderEntity>()
    );

    return new PageUtils(page);
  }

  @Override
  public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
    /**
     * 在Feign调用远程服务的时候，会创建一个新的请求，但该请求不会携带老请求中的任何请求头，从而导致了请求头丢失，无法获取Cookit
     * 解决方法：添加一个RequestInterceptor拦截器并将老请求中的请求头设置到新请求中即可（参考com.mune.gulimall.order.config.FeignConfig）
     *
     * Feign使用线程池异步编排调用远程服务导致无法获取请求对象
     * 由于获取请求对象，本质上就是还是用了ThreadLocal机制，没加入异步编排之前，一次请求的所有操作都是在一个线程中进行，所以可以共享Request对象
     * 但是使用了异步编排后，相当于为其任务额外开启了单独的线程，从而导致无法进行共享
     * 解决方法：在父线程中（创建异步编排的线程）中获取当前RequestAttributes上下文，并在任务中重新设置上即可
     */
    MemberSessionTo memberSessionTo = LoginUserInterceptor.orderThread.get();
    OrderConfirmVo confirmVo = new OrderConfirmVo();
    // 获取当前请求中的上下文
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
      // 在异步编排任务中为新创建的线程设置上下文
      RequestContextHolder.setRequestAttributes(requestAttributes);
      confirmVo.setAddress(memberFeignService.getAddress(memberSessionTo.getId()));
    }, executor);
    CompletableFuture<Void> getCartItemFuture = CompletableFuture.runAsync(() -> {
      RequestContextHolder.setRequestAttributes(requestAttributes);
      confirmVo.setItems(cartFeignService.currentUserCartItems());
    }, executor).thenRunAsync(() -> {
      List<Long> collect = confirmVo.getItems().stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
      R skusHasStock = wareFeignService.getSkusHasStock(collect);
      List<SkuStockVo> data = skusHasStock.getData(new TypeReference<List<SkuStockVo>>() {
      });
      if (data != null) {
        Map<Long, Boolean> hasStocks = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
        confirmVo.setStocks(hasStocks);
      }

    }, executor);
    Integer integration = memberSessionTo.getIntegration();
    confirmVo.setIntegration(integration);
    // 防重令牌
    String token = UUID.randomUUID().toString().replace("-", "");
    redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberSessionTo.getId(), token, 30, TimeUnit.MINUTES);
    confirmVo.setOrderToken(token);
    CompletableFuture.allOf(getAddressFuture, getCartItemFuture).get();
    return confirmVo;
  }

  @Transactional
  @Override
  public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
    orderSubmitVoThreadLocal.set(vo);
    MemberSessionTo memberSessionTo = LoginUserInterceptor.orderThread.get();
    SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
    responseVo.setCode(0);
    String orderToken = vo.getOrderToken();
    // Lua脚本保证获取和删除令牌的原子性
    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
    Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberSessionTo.getId()), orderToken);
    if (result == null || result != 1L) {
      // 验证失败
      responseVo.setCode(1);
      return responseVo;
    } else {
      // 验证成功，进行验价 锁库存等操作
      OrderCreateTo order = createOrder();
      // 验价
      BigDecimal payAmount = order.getOrder().getPayAmount();
      BigDecimal payPrice = vo.getPayPrice();
      if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
        // 金额对比成功
        saveOrder(order);
        // 库存锁定
        WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
        wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
        List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
          OrderItemVo orderItemVo = new OrderItemVo();
          orderItemVo.setSkuId(item.getSkuId());
          orderItemVo.setCount(item.getSkuQuantity());
          orderItemVo.setTitle(item.getSkuName());
          return orderItemVo;
        }).collect(Collectors.toList());
        wareSkuLockVo.setLocks(collect);
        R r = wareFeignService.orderLockStock(wareSkuLockVo);
        if (r.getCode() == 0) {
          responseVo.setOrder(order.getOrder());
          //TODO给MQ发送订单创建成功的消息
          rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
        } else {
          throw new NoStockException(1L);
        }
        return responseVo;
      } else {
        // 金额对比失败
        responseVo.setCode(2);
        return responseVo;
      }
    }
  }

  @Override
  public OrderEntity getOrderByOrderSn(String orderSn) {

    return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

  }

  @Override
  public void closeOrder(OrderEntity entity) {
    OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", entity.getOrderSn()));
    if (orderEntity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())) {
      OrderEntity update = new OrderEntity();
      update.setId(orderEntity.getId());
      update.setStatus(OrderStatusEnum.CANCLED.getCode());
      // 关闭订单
      this.updateById(update);
      // 发送消息给mq通知库存服务进行解锁
      OrderTo orderTo = new OrderTo();
      BeanUtils.copyProperties(orderEntity, orderTo);
      rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
    }

  }

  @Override
  public PayVo getPayByOrderSn(String orderSn) {

    PayVo payVo = new PayVo();
    OrderEntity order = this.getOrderByOrderSn(orderSn);
    payVo.setTotal_amount(order.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());
    payVo.setOut_trade_no(order.getOrderSn());
    List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
    OrderItemEntity entity = order_sn.get(0);
    payVo.setSubject(entity.getSkuName());
    payVo.setBody(entity.getSkuAttrsVals());
    return payVo;
  }

  @Override
  public PageUtils queryPageItem(Map<String, Object> params) {
    MemberSessionTo memberSessionTo = LoginUserInterceptor.orderThread.get();
    IPage<OrderEntity> page = this.page(new Query<OrderEntity>().getPage(params), new QueryWrapper<OrderEntity>().eq("member_id", memberSessionTo.getId()).orderByDesc("id"));
    List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
      List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
      order.setItemEntities(itemEntities);
      return order;
    }).collect(Collectors.toList());
    page.setRecords(order_sn);
    return new PageUtils(page);
  }

  @Override
  public String handlePayResult(PayAsyncVo payVo) {

    // 保存交易流水
    PaymentInfoEntity infoEntity = new PaymentInfoEntity();
    infoEntity.setAlipayTradeNo(payVo.getTrade_no());
    infoEntity.setOrderSn(payVo.getOut_trade_no());
    infoEntity.setPaymentStatus(payVo.getTrade_status());
    infoEntity.setCallbackTime(payVo.getNotify_time());
    paymentInfoService.save(infoEntity);
    if (payVo.getTrade_status().equals("TRADE_SUCCESS") || payVo.getTrade_status().equals("TRADE_FINISHED")) {
      String outTradeNo = payVo.getOut_trade_no();
      this.baseMapper.updateOrderPayedStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
      return "success";
    }
    return "error";
  }

  @Override
  public void createSeckillOrder(SeckillOrderTo orderTo) {

    OrderEntity orderEntity = new OrderEntity();
    orderEntity.setOrderSn(orderTo.getOrderSn());
    orderEntity.setMemberId(orderTo.getMemberId());
    orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
    BigDecimal multiply = orderTo.getSeckillPrice().multiply(new BigDecimal(orderTo.getNum().toString()));
    orderEntity.setPayAmount(multiply);
    this.save(orderEntity);
    // 保存订单信息
    OrderItemEntity orderItemEntity = new OrderItemEntity();
    orderItemEntity.setOrderSn(orderTo.getOrderSn());
    orderItemEntity.setRealAmount(multiply);
    orderItemEntity.setSkuQuantity(orderTo.getNum());
    //保存订单
    this.save(orderEntity);
    //保存商品的spu信息
    R spuInfo = productFeignService.getSpuInfoBySkuId(orderTo.getSkuId());
    SpuInfoVo spuInfoData = spuInfo.getData(new TypeReference<SpuInfoVo>() {
    });
    orderItemEntity.setSpuId(spuInfoData.getId());
    orderItemEntity.setSpuName(spuInfoData.getSpuName());
    orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

    //保存订单项数据
    orderItemService.save(orderItemEntity);
  }

  private void saveOrder(OrderCreateTo order) {
    OrderEntity orderEntity = order.getOrder();
    orderEntity.setModifyTime(new Date());
    orderEntity.setCreateTime(new Date());
    this.baseMapper.insert(orderEntity);
    List<OrderItemEntity> orderItems = order.getOrderItems();
    orderItemService.saveBatch(orderItems);
  }

  private OrderCreateTo createOrder() {
    OrderCreateTo createTo = new OrderCreateTo();
    // 订单编号
    String orderSn = IdWorker.getTimeId();
    OrderEntity orderEntity = buildOrder(orderSn);
    // 获取所有订单项
    List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
    // 验价
    computePrice(orderEntity, orderItemEntities);
    createTo.setOrder(orderEntity);
    createTo.setOrderItems(orderItemEntities);
    return createTo;
  }

  private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
    // 订单价格相关
    BigDecimal total = new BigDecimal("0.0");
    BigDecimal coupon = new BigDecimal("0.0");
    BigDecimal integration = new BigDecimal("0.0");
    BigDecimal promotion = new BigDecimal("0.0");
    BigDecimal gift = new BigDecimal("0.0");
    BigDecimal growth = new BigDecimal("0.0");
    for (OrderItemEntity entity : orderItemEntities) {
      coupon = coupon.add(entity.getCouponAmount());
      integration = integration.add(entity.getIntegrationAmount());
      promotion = promotion.add(entity.getPromotionAmount());
      total = total.add(entity.getRealAmount());
      gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
      growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
    }
    orderEntity.setTotalAmount(total);
    // 应付金额 总金额 + 运费
    orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
    orderEntity.setCouponAmount(coupon);
    orderEntity.setIntegrationAmount(integration);
    orderEntity.setPromotionAmount(promotion);
    orderEntity.setIntegration(gift.intValue());
    orderEntity.setGrowth(growth.intValue());
    orderEntity.setDeleteStatus(0);
  }

  private OrderEntity buildOrder(String orderSn) {
    MemberSessionTo memberSessionTo = LoginUserInterceptor.orderThread.get();
    OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
    OrderEntity entity = new OrderEntity();
    entity.setMemberId(memberSessionTo.getId());
    entity.setOrderSn(orderSn);
    // 获取收货地址信息
    R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
    FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
    });
    // 设置运费信息
    entity.setFreightAmount(fareResp.getFare());
    // 设置收货人信息
    entity.setReceiverCity(fareResp.getAddress().getCity());
    entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
    entity.setReceiverName(fareResp.getAddress().getName());
    entity.setReceiverPhone(fareResp.getAddress().getPhone());
    entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
    entity.setReceiverProvince(fareResp.getAddress().getProvince());
    entity.setReceiverRegion(fareResp.getAddress().getRegion());
    entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
    entity.setAutoConfirmDay(7);

    return entity;
  }

  /**
   * 构建订单项，将购物车对象转换为订单项对象
   *
   * @return
   */
  private List<OrderItemEntity> buildOrderItems(String orderSn) {
    List<OrderItemVo> orderItemVos = cartFeignService.currentUserCartItems();
    if (orderItemVos != null && orderItemVos.size() > 0) {
      List<OrderItemEntity> itemEntities = orderItemVos.stream().map(cartItem -> {
        OrderItemEntity itemEntity = buildOrderItem(cartItem);
        itemEntity.setOrderSn(orderSn);
        return itemEntity;
      }).collect(Collectors.toList());
      return itemEntities;
    }
    return null;
  }

  private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
    OrderItemEntity itemEntity = new OrderItemEntity();
    // spu信息
    Long skuId = cartItem.getSkuId();
    R r = productFeignService.getSpuInfoBySkuId(skuId);
    SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
    });
    itemEntity.setSpuId(data.getId());
    itemEntity.setSpuBrand(data.getBrandId().toString());
    itemEntity.setSpuName(data.getSpuName());
    itemEntity.setSpuPic(data.getSpuDescription());
    itemEntity.setCategoryId(data.getCatalogId());
    // sku信息
    itemEntity.setSkuId(cartItem.getSkuId());
    itemEntity.setSkuName(cartItem.getTitle());
    itemEntity.setSkuPic(cartItem.getImage());
    itemEntity.setSkuPrice(cartItem.getPrice());
    String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
    itemEntity.setSkuAttrsVals(skuAttr);
    itemEntity.setSkuQuantity(cartItem.getCount());
    // 积分信息
    itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
    itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());

    // 订单项价格信息
    itemEntity.setPromotionAmount(new BigDecimal("0"));
    itemEntity.setCouponAmount(new BigDecimal("0"));
    itemEntity.setIntegrationAmount(new BigDecimal("0"));
    BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
    orign = orign.subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getIntegrationAmount());
    itemEntity.setRealAmount(orign);
    return itemEntity;

  }
}